package se.recept.kollen.module.bean;

import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.ValidationError;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;
import se.recept.kollen.model.Customer;
import se.recept.kollen.module.extension.FragmentResolution;
import se.recept.kollen.module.extension.NoContentResolution;

/**
 *
 * @author jocke
 */
public class DefaultActionBean implements ActionBean, ValidationErrorHandler {

    private ActionBeanContext context;

    private static final String CUSTOMER = DefaultActionBean.class.getPackage().getName() + ".customer";

    private static final Logger LOG = Logger.getLogger(LoginActionBean.class.getName());
    

    @Override
    public void setContext(ActionBeanContext abc) {
        this.context = abc;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }

    public Customer getCustomer() {
        return (Customer) getSessionAttribute(CUSTOMER);
    }

    public void setCustomer(Customer customer) {
        setSessionAttribute(customer, CUSTOMER);
    }

    protected void setSessionAttribute(Customer customer, String name) {
        getContext().getRequest().getSession().setAttribute(name, customer);
    }

    protected Object getSessionAttribute(String name) {
        return getContext().getRequest().getSession().getAttribute(name);
    }

    public boolean isErroneous() {
        return !context.getValidationErrors().isEmpty();
    }


    
    @Override
    public Resolution handleValidationErrors(ValidationErrors errors) throws Exception {
        
        for (Map.Entry<String, List<ValidationError>> entry : errors.entrySet()) {
            LOG.log(Level.INFO, "Key {0} {1}", new Object[]{entry.getKey(), entry.getValue()});
        }

        if (context.getRequest().getParameterValues("errorfragment") != null) {
            return new FragmentResolution().setStatus(422);

        } else {
            return new NoContentResolution();
        }

    }
}
